var util = require('../../utils/util.js');
const app = getApp();
Page({
  data: {
    addressList: [],
  },
  onLoad: function (options) {
    // 页面初始化 options为页面跳转所带来的参数
    this.setData({
      type: options.type
    })
  },
  
  onShow: function () {
    // 页面显示
    this.getAddressList();
  },
  getAddressList() {
    let that = this;
    wx.getStorage({
      key: 'openid',
      success: function(res) {
        let openid = res.data
        wx.request({
          url: app.globalData.URL + '/app/personal/address?openid=' + openid,
          success: function (res) {
            console.log("AddressList", res.data)
            that.setData({
              addressList: res.data.qhcDelivery,
            })
          }
        })
      },
    })
    
  },
  addressAddOrUpdate(event) {
    wx.navigateTo({
      url: '../addressAdd/addressAdd?id=' + event.currentTarget.dataset.addressId
    })
  },
  deleteAddress(event) {
    let that = this;
    wx.showModal({
      title: '',
      content: '确定要删除地址？',
      success: function (res) {
        if (res.confirm) {
          let addressId = event.currentTarget.dataset.addressId;
          console.log(event)
          wx.getStorage({
            key: 'openid',
            success: function(res) {
              let openid = res.data
              
              wx.request({
                url: app.globalData.URL + '/app/personal/delAddress?id=' + addressId + '&openid=' + openid,
                success: function (res) {
                  if (res.data.flag == true) {
                    wx.showToast({
                      title: '删除成功',
                    })
                
                    that.getAddressList();
                    
                  } else {
                    util.showErrorToast('网络错误，请稍后再试');
                  }
                }
              })
            },
          })
          
        }
      }
    })
    return false;

  },

  toShoppingList:function(e){
    //如果前一个页面传来的的type=1 传值回跳到购物清单
    if(this.data.type == 1){
      var pages = getCurrentPages();   //当前页面
      var prevPage = pages[pages.length - 2];    //上一页面
      prevPage.setData({
        //直接给上一页面赋值
        name: e.currentTarget.dataset.name,
        phone: e.currentTarget.dataset.phone,
        address: e.currentTarget.dataset.address,
        dlid: this.data.addressList[0].id
      })
      wx.navigateBack({
        //返回上一页面
        delta: 1,
      })
    }
  }

})